package com.lsfb.signln.Login;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;

import com.lsfb.signln.Index.IndexActivity;
import com.lsfb.signln.Login.Face.FirstFaceActivity;
import com.lsfb.signln.Login.Forget.ForgetActicity;
import com.lsfb.signln.R;
import com.lsfb.signln.Utils.DeviceUtil;
import com.lsfb.signln.Utils.LittleUtils;
import com.lsfb.signln.Utils.URLString;
import com.zgscwjm.lsfbbasetemplate.Event.EventAnnotation;
import com.zgscwjm.lsfbbasetemplate.LsfbActivity;
import com.zgscwjm.lsfbbasetemplate.LsfbAppManager;
import com.zgscwjm.lsfbbasetemplate.annotation.ContentView;
import com.zgscwjm.lsfbbasetemplate.annotation.OnClick;
import com.zgscwjm.lsfbbasetemplate.annotation.ViewInject;
import com.zgscwjm.lsfbbasetemplate.config.Config;
import com.zgscwjm.lsfbbasetemplate.internet.BaseInternet;
import com.zgscwjm.lsfbbasetemplate.utils.SPUtils;
import com.zgscwjm.lsfbbasetemplate.utils.T;

import java.util.HashMap;

import cn.jpush.android.api.JPushInterface;

/**
 * Created by Administrator on 2018/1/22 0022.
 */
@ContentView(R.layout.aty_login)
public class LoginActivity extends LsfbActivity {

    /**
     * 手机号码
     */
    @ViewInject(R.id.aty_login_et_phone)
    private EditText et_phone;

    /**
     * 密码
     */
    @ViewInject(R.id.aty_login_et_pwd)
    private EditText et_pwd;

    /**
     * 用户名
     */
    private String username = "";
    /**
     * 密码
     */
    private String password = "";

    /**
     * 设备号
     */
    private String device_id;


    @Override
    public void initView() {
        username = String.valueOf(SPUtils.get(this, "et_username", ""));
        password = String.valueOf(SPUtils.get(this, "et_password", ""));
        et_phone.setText(username);
        et_pwd.setText(password);

        try {
            device_id = new DeviceUtil(this).getDeviceId();
        } catch (SecurityException e) {
            device_id = "null";
            T.showShort(LoginActivity.this, "获取设备号出错,请给予相关手机权限,否则应用无法正常运行");
        }
//        netWorkWarranty();
    }

//    /**
//     * 联网授权
//     */
//    private void netWorkWarranty() {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                Manager manager = new Manager(LoginActivity.this);
//                LivenessLicenseManager licenseManager = new LivenessLicenseManager(LoginActivity.this);
//                manager.registerLicenseManager(licenseManager);
//
//                manager.takeLicenseFromNetwork(device_id);
//                if (licenseManager.checkCachedLicense() <= 0){
//                    finish();
//                    ConUtil.showToast(LoginActivity.this, "联网授权失败");
//                }else {
//                    LsfbLog.e("联网授权成功");
//                }
//            }
//        }).start();
//    }

    @Override
    public void initEvent() {

    }

    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.aty_login_btn_login, R.id.aty_login_btn_forget})
    public void onClikc(View view) {
        switch (view.getId()) {
            //登录
            case R.id.aty_login_btn_login:
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(et_phone.getWindowToken(), 0);
                imm.hideSoftInputFromWindow(et_pwd.getWindowToken(), 0);
//                startActivity(new Intent(this, IndexActivity.class));
                login();
                break;
            //忘记密码
            case R.id.aty_login_btn_forget:
                startActivity(new Intent(this, ForgetActicity.class));
                break;
        }
    }

    @Override
    public void initData() {

    }

    /**
     * 登录
     */
    public void login() {

        if (et_phone.getText().toString().isEmpty()) {
            T.showShort(this, "请输入用户名");
            return;
        }

        if (et_pwd.getText().toString().isEmpty()) {
            T.showShort(this, "请输入密码");
            return;
        } else if (et_pwd.getText().toString().length() > 9 || et_pwd.getText().toString().length() < 6) {
            T.showShort(this, "请输入6~9位字符的密码");
        }

        if (device_id.equals("null")) {
            T.showShort(this, "获取设备号出错,请给予相关手机权限,否则应用无法正常运行");
            return;
        }
        HashMap<String, String> hashMap = new HashMap<String, String>();
        hashMap.put("username", et_phone.getText().toString());
        hashMap.put("password", et_pwd.getText().toString());
//        hashMap.put("password", MD5.GetMD5Code(et_pwd.getText().toString()));
        hashMap.put("jpushid", JPushInterface.getRegistrationID(getApplicationContext())
        );
        hashMap.put("deviceid", device_id);
        new BaseInternet().getData(URLString.LOGIN, hashMap, LoginBean.class, new LoginEvent<LoginBean>(), false);
    }

    @EventAnnotation
    public void LoginEvent(LoginEvent<LoginBean> event) {
        switch (event.getCode()) {
            case 200:
                Config.setUserId(event.getData().getUserid());
                LittleUtils.saveuser(Config.getUserId(), getApplicationContext());
                SPUtils.put(this, "et_username", et_phone.getText().toString());
                SPUtils.put(this, "et_password", et_pwd.getText().toString());
//                //第一次登陆
                if (event.getData().getIsFirst().equals("1")) {
                    startActivity(new Intent(this, FirstFaceActivity.class).putExtra("type", "1"));
                } else {
                    startActivity(new Intent(this, IndexActivity.class));
                }
                break;
            case 1006:
                T.showShort(this, "您的账号已在其它设备登录，请重登录");
                LittleUtils.exit(this);
                startActivity(new Intent(this, LoginActivity.class));
                break;
            default:
                T.showShort(this, event.getMsg());
                break;
        }
    }

    //点击退出弹出确认提示框
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            dialog();
            return true;
        }
        return true;
    }

    protected void dialog() {

//    通过AlertDialog.Builder这个类来实例化我们的一个AlertDialog的对象
        AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.MyAlertDialogStyle);
//    设置Title的图标
//        builder.setIcon(R.mipmap.ic_launcher);
//    设置Title的内容
        builder.setTitle("温馨提示");
//    设置Content来显示一个信息
        builder.setMessage("确定要退出应用吗？");
//    设置一个PositiveButton
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                LsfbAppManager.getAppManager().finishAllActivity();
                android.os.Process.killProcess(android.os.Process.myPid());
            }
        });
//    设置一个NegativeButton
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {

            }
        });
//    显示出该对话框
        builder.show();
    }

    /**
     * 点击空白区域隐藏键盘.
     */
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            if (this.getCurrentFocus() != null) {
                if (this.getCurrentFocus().getWindowToken() != null) {
                    imm.hideSoftInputFromWindow(this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                }
            }
        }
        return super.onTouchEvent(event);
    }
}
